package com.lg.mq.consumer;

import com.lg.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Random;

import static com.lg.mockpersistent.MockPersist.*;

/**
 * 仅配置死信队列的消费者，消息到期后由死信队列消费者来根据订单状态进行相应的业务处理
 */
@Component
public class PayMsgListener {

    private Random random = new Random();

    /**
     * 配置死信队列的消费者
     *
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = RabbitConfig.QUEUE_PAY_DLX, containerFactory = RabbitConfig.SINGLE_LISTENER_FACTORY)
    public void processDlxPayMsg(Message message, Channel channel) throws IOException {
        String orderId = new String(message.getBody());
        String orderFinalStatus;

        String orderStatus = ORDERS.get(orderId);

        // 订单处于等待支付状态，但此时已到时，即订单支付超时
        if (WAITING_PAY.equals(orderStatus)) {
            ORDERS.put(orderId, PAY_TIMEOUT);
            orderFinalStatus = PAY_TIMEOUT;
        } else {
            // 订单处于支付成功的状态则说明一切正常，即订单支付成功，此时不需做额外操作，消费掉该条消息即可
            orderFinalStatus = orderStatus;
        }

        // 手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        System.out.println("死信队列接收到订单[" + orderId + "]并ack，订单最终支付状态：" + orderFinalStatus + "。");
    }


    /**
     * 正常队列的消费者
     *
     * @param message
     * @param channel
     * @throws IOException
     * @throws InterruptedException
     */
    /*@RabbitHandler
    @RabbitListener(queues = RabbitConfig.QUEUE_PAY_NORMAL, containerFactory = RabbitConfig.SINGLE_LISTENER_FACTORY)
    public void processNormalPayMsg(Message message, Channel channel) throws IOException, InterruptedException {
        if (random.nextInt() % 2 == 0) {
            System.out.println("正常队列接收到消息并ack：" + new String(message.getBody()));
        } else {
            TimeUnit.SECONDS.sleep(3);
            // 手动应答
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("正常队列接收到消息并reject：" + new String(message.getBody()));
        }
    }*/


}
